﻿namespace Future.Web.Middlewares
{
    /// <summary>
    /// 统一返回中间件
    /// </summary>
    public class UnifyResultStatusCodesMiddleware
    {
        /// <summary>
        /// 请求委托
        /// </summary>
        private readonly RequestDelegate _next;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        public UnifyResultStatusCodesMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 中间件执行方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            await _next(context);

            // 只有请求错误（短路状态码）才支持规范化处理
            if (context.Response.StatusCode < 400 || context.Response.StatusCode == 404) return;

            int statusCode = context.Response.StatusCode;
            // 设置返回的状态码为 200
            context.Response.StatusCode = StatusCodes.Status200OK;

            switch (statusCode)
            {
                // 处理 401 状态码
                case StatusCodes.Status401Unauthorized:
                    await context.Response.WriteAsJsonAsync(ResultVo.Expire(msg: "无权限"));
                    break;
                // 处理 403 状态码
                case StatusCodes.Status403Forbidden:
                    await context.Response.WriteAsJsonAsync(ResultVo.Fail(ResultCodeEnum.Forbidden, "禁止访问"));
                    break;
                case StatusCodes.Status415UnsupportedMediaType:
                    await context.Response.WriteAsJsonAsync(ResultVo.Fail(ResultCodeEnum.UnsupportedMediaType, "不支持的媒体类型"));
                    break;

                default: break;
            }
        }
    }
}
